﻿using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class GenericParameterRule : ILRule<GenericParameterHandle>
    {
        [ILInfo]
        public EntityHandle Parent { get; }

        [ILInfo]
        public GenericParameterAttributes Attributes { get; }

        [ILInfo(true)]
        public string Name { get; }

        [ILInfo(true)]
        public int Index { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public GenericParameterConstraintHandleCollection Constraints { get; }

        public CustomAttributeHandleCollection CustomAttributes { get; }

        public GenericParameterRule(
            EntityHandle parent,
            GenericParameterAttributes attributes,
            string name,
            int index)
            : base()
        {
            Parent = parent;
            Attributes = attributes;
            Name = name;
            Index = index;
        }

        public GenericParameterRule(MetadataReader reader, GenericParameterHandle genericParameterHandle)
            : base(reader)
        {
            GenericParameter genericParameter = reader.GetGenericParameter(genericParameterHandle);
            Parent = genericParameter.Parent;
            Attributes = genericParameter.Attributes;
            Name = reader.GetString(genericParameter.Name);
            Index = genericParameter.Index;
            Constraints = genericParameter.GetConstraints();
            CustomAttributes = genericParameter.GetCustomAttributes();
        }

        public override GenericParameterHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddGenericParameter(
                parent: Parent,
                attributes: Attributes,
                name: Name == null ? default : builder.GetOrAddString(Name),
                index: Index);
        }
    }
}